package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyCommentRepository;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private StrategyThemeRepository repository;
    @Autowired
    private StrategyCommentRepository commentRepository;

    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        repository.save(strategyTheme);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        repository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyTheme get(String id) {
        StrategyTheme strategyTheme =repository.findById(id).orElse(null);
        return strategyTheme;
    }

    @Override
    public List<StrategyTheme> list() {
        return repository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {
        //分页查询
        //查询对象
        //1: 查询总数:total
        Query query = new Query();
        long total = template.count(query, StrategyTheme.class);
        if(total == 0){
            return Page.empty();  //空的分页对象
        }
        //2: 每页显示条数集合: list
        //设置页面显示条数, 还有当前页
        //1 当前页 2 每页的条数 3 排序规则 4 排序字段
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "_id");
        query.with(pageable);
        List<StrategyTheme> list = template.find(query, StrategyTheme.class);

        //3:封装page对象
        return new PageImpl<StrategyTheme>(list,pageable,total);
    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        if (!(StringUtils.hasLength(strategyTheme.getId()))){
            strategyTheme.setId(null);
            this.save(strategyTheme);
        }else {
            this.update(strategyTheme);

        }
    }


    @Override
    public List<StrategyTheme> getAll() {
        List<StrategyTheme> list = repository.findAll();
        return list;
    }


}
